import React, { Component } from 'react';

import {
    StyleSheet,
    Text,
    View,
    TouchableOpacity,
    Image,
    Linking,
    Alert, DeviceEventEmitter, FlatList, ActivityIndicator, Platform, Dimensions,
} from 'react-native';
import Header from '../../components/header';
import HttpUtils from '../../utils/HttpUtils';
import HttpUrls from '../../utils/HttpUrls';
import { getImgUrl } from '../../utils/ComFunction';
import Loading from "../../utils/Loading";
import Constant from '../../utils/Constant';
import NoData from "../../utils/NoData";
import BuyerSetLabelPage from "./BuyerSetLabelPage";
import AlertCommonView from "../../components/Tool/AlertCommonView";
import {ToastToUser} from "../../utils/CustomToast";
import SeekItemView from "./seekComponents/SeekItemView";
import {empty} from "react-native-model/src/vendor/Helper";
import {deviceInfoEmitter} from "react-native-device-info/lib/typescript/internal/asyncHookWrappers"; //全局变量
let navigation;

const isIos = Platform.OS == 'ios';
const screenW = Dimensions.get('window').width;
const screenH = Dimensions.get('window').height;

export default class BuyerInfoPage extends Component {
    constructor(props) {
        super(props);
        this.state = {
            buyerDetail: {},
            tagList: [],
            limitTagList: [],
            allTagList: [],
            // 是否关注
            isFollow: false,
            showTagMore: false,

            isRefresh: false,
            showFoot: false, // true：已加载完成,没有更多数据
            pageNo: 1,
            pageSize: 20,

            // 我发布的求购信息
            seekingList: [],

            isFranchisee: Constant.userInfo.isFranchisee,//是否加盟商 0：否，1：是
        };
    }
    componentDidMount() {
        this.setLable = DeviceEventEmitter.addListener('BuyerSetLabelPage', (data) => {
            this.loadData();
            this.setState({
                showTagMore: false,
                tagList: this.state.limitTagList,
            })
        })
        this.ApplyCarFormPage = DeviceEventEmitter.addListener('ApplyCarFormPage', (data) => {
            this.refreshData()
        })
        this.loadData()
        this.getBuyerSeekList()
    }
    componentWillUnmount() {
        if (this.setLable) {
            this.setLable.remove();
        }
        if (this.ApplyCarFormPage) {
            this.ApplyCarFormPage.remove();
        }
    }
    //加载数据
    loadData() {
        //读取页面传入参数
        let params = this.props.route.params;
        let buyerId = params.buyerId
        this.Loading.show();
        HttpUtils.getRequest(HttpUrls.queryBuyerDetail, { buyerId: buyerId })
            .then(result => {
                if (result.code === 0) {
                    let tempTagList = [];
                    let limitTempTagList = [];
                    //判断如果存在标签列表
                    if (result.data?.buyerTags?.length > 0) {
                        //循环标签列表
                        result.data.buyerTags.forEach(tagItem => {
                            if(tagItem.tagValueText !== '不限'){
                                tempTagList.push(tagItem);
                            }
                        })
                    }
                    if (result.data?.limitShowBuyerTags?.length > 0) {
                        //循环标签列表
                        result.data.limitShowBuyerTags.forEach(tagItem => {
                            if(tagItem.tagValueText !== '不限'){
                                limitTempTagList.push(tagItem);
                            }
                        })
                    }

                    this.checkBuyerFollow();

                    this.setState({
                        buyerDetail: result.data,
                        tagList: limitTempTagList,
                        limitTagList: limitTempTagList,
                        allTagList: tempTagList
                    })
                }
            }).finally(e => {this.Loading.hide();})
    }

    // 查询是否已经关注
    checkBuyerFollow(){
        let params = this.props.route.params;
        let buyerId = params.buyerId
        this.Loading.show()
        HttpUtils.getRequest(HttpUrls.checkBuyerFollow, {userId: Constant.userInfo.userId, buyerId: buyerId}).then(result => {
            console.log('查询是否已经关注',result.data)
            if(result.code === 0){
                let data = result.data;
                if(data.isFollow){
                    this.setState({
                        isFollow: true
                    })
                }else {
                    this.setState({
                        isFollow: false
                    })
                }
            }
        }).finally(e => {this.Loading.hide();})
    }

    // 关注和取消关注
    switchFollow(){
        //读取页面传入参数
        let params = this.props.route.params;
        let buyerId = params.buyerId ?? 0
        let type  = 1 // 1 添加关注 0 取消关注
        this.Loading.show();
        if(this.state.isFollow){
            type = 0
        }
        HttpUtils.getRequest(HttpUrls.switchFollow, { userId: Constant.userInfo.userId, buyerId: buyerId, type: type })
            .then(result => {
                console.log('关注结果',result)
                if (result.code === 0) {
                    if(result.data){
                        this.setState({
                            isFollow: !this.state.isFollow,
                        })
                        DeviceEventEmitter.emit('commonEvent', {type: 'follow', fromPage: 'BuyerInfoPage'});
                    }
                }else{
                    ToastToUser(result?.msg || '操作失败')
                }
            }).finally(e => {this.Loading.hide();})
    }


    // 求购信息列表
    getBuyerSeekList(){
        const { buyerId = 0 } = this.props.route.params || {};
        HttpUtils.postRequest(HttpUrls.seekingQueryPage, { pageNo: this.state.pageNo, pageSize: this.state.pageSize, buyerId: buyerId, optionShowCarNum: 1 })
            .then(result => {
                let data = result.data;
                if (data) {
                    let resultList = data.resultList;
                    if (resultList && resultList.length > 0) {
                        this.setState({
                            seekingList: this.state.seekingList.concat(resultList),
                            isRefresh: false,
                        });
                    } else {
                        this.setState({
                            isRefresh: false
                        });
                        if(this.state.seekingList.length > 0){
                            this.setState({
                                showFoot: true,
                            });
                        }
                    }
                } else {
                    this.setState({
                        isRefresh: false,
                    });
                }
            }).finally(e => {
        })
    }

    // 替换城市后缀
    replaceCitySuffix(cityName) {
        if (!cityName) return '';
        return cityName.replace(/(省|市|区|自治区|自治州|特别行政区)$/g, '');
    }

    render() {
        navigation = this.props.navigation;
        return (
            <View style={styles.container}>
                <Header navigation={navigation} Title={'买手详情'}  />
                <View style={styles.infoContainer}>
                    <View style={{width: '20%'}}>
                        {this.state.buyerDetail?.avatar ? (
                            <Image
                                style={styles.avatarStyle}
                                source={{
                                    uri: getImgUrl(this.state.buyerDetail?.avatar),
                                }}
                            />
                        ) : (
                            <Image
                                source={require('source/image/seekCenter/default_avatar.png')}
                                style={styles.avatarStyle}
                            />
                        )}
                        <Text style={styles.regionTag}>
                            {this.replaceCitySuffix(this.state.buyerDetail?.provinceName) ?? ''} {this.replaceCitySuffix(this.state.buyerDetail?.cityName) ?? '未设置'}
                        </Text>
                    </View>
                    <View style={{width: '54%', marginLeft: 5}}>
                        <TouchableOpacity activeOpacity={0.7} onPress={() =>{
                            if(this.state.buyerDetail?.merchantAbbreviation) {
                                console.log('商户详情',this.state.buyerDetail?.merchantId)
                                navigation.navigate('CompanyInfoPage', {
                                    merchantId: this.state.buyerDetail?.merchantId,
                                    // category: item.specializedTitle || '',
                                });
                            }
                        }}>
                            <Text numberOfLines={1} style={{flexDirection: 'row', width: '100%'}}>
                                <Text style={styles.nameText}>
                                    {this.state.buyerDetail?.fullname}
                                </Text>
                                <Text> </Text>
                                <Text style={{fontSize:13, color:'#FFA500', marginLeft: 6}}>
                                    @{this.state.buyerDetail?.merchantAbbreviation ?? '暂无'}
                                </Text>
                            </Text>
                        </TouchableOpacity>


                        <Text numberOfLines={3} style={styles.introText}>
                            简介: {this.state.buyerDetail?.preferences ?? '暂无'}
                        </Text>
                    </View>
                    <View style={styles.actionButtons}>

                        <TouchableOpacity
                            activeOpacity={0.7}
                            onPress={() => this.makeCall(this.state.buyerDetail?.phone)}
                            style={styles.phoneButtonContainer}
                        >
                            <Text style={styles.phoneButtonText}>电话</Text>
                        </TouchableOpacity>

                        <TouchableOpacity activeOpacity={0.7} onPress={() => this.switchFollow()}>
                            {this.state.isFollow ?
                                <View style={[styles.phoneButtonContainer, { marginTop: 10, backgroundColor: '#F5F5F5', color: '#666666' }]}>
                                    <Text style={[styles.phoneButtonText, { }]} >
                                        取消关注
                                    </Text>
                                </View>
                                :
                                <View style={[styles.phoneButtonContainer, { marginTop: 10, backgroundColor: '#F5F5F5', color: '#333' }]}>
                                    <Text style={[styles.phoneButtonText]} >
                                        关注
                                    </Text>
                                </View>
                            }
                        </TouchableOpacity>
                    </View>
                </View>

                <View style={styles.preferenceContainer}>
                    <Text style={styles.sectionTitle}>
                        偏好标签
                    </Text>
                    <View style={styles.tagsContainer}>
                        {this.state.tagList.map((item, index) => (
                            <View style={styles.tagItem}>
                                <Text key={index} style={styles.tagItemText}>
                                    {item?.tagValueText}
                                </Text>
                            </View>
                        ))}
                        <TouchableOpacity activeOpacity={0.7} style={styles.tagItemMore} onPress={() => {
                            if (!this.state.showTagMore) {
                                this.setState({
                                    tagList: this.state.allTagList
                                })
                            } else {
                                this.setState({
                                    tagList: this.state.limitTagList
                                })
                            }
                            this.setState({
                                showTagMore: !this.state.showTagMore
                            })
                        }}>
                            <Text style={styles.tagItemMoreText}>{this.state.showTagMore ? '收起' : '查看全部'}</Text>
                        </TouchableOpacity>

                        {/*<Text style={styles.flexGrow} />*/}
                    </View>
                </View>

                {this.renderList()}

                {this.state.isFranchisee == 1 && (
                    <View style={styles.butBox}>
                        <TouchableOpacity activeOpacity={0.8} onPress={() => {
                            navigation.navigate('SeekingCarPage', {
                                id: -1,
                                merchantId: this.state.buyerDetail?.merchantId || null,
                                userId: this.state.buyerDetail?.userId || null,
                            })
                        }}>
                            <View style={styles.but}>
                                <Text style={styles.butText}>快速推荐</Text>
                            </View>
                        </TouchableOpacity>
                    </View>
                )}

                <Loading onRef={ref => (this.Loading = ref)} />

            </View>
        );
    }

    renderList() {
        return (
            <View
                style={{
                    flex: 1,
                    marginBottom: Constant.isIPhoneX ? Constant.bottomHeight + 0 : 0,
                }}>
                <FlatList
                    data={this.state.seekingList}
                    renderItem={this.renderItemView.bind(this)}
                    extraData={this.state}
                    onRefresh={this.refreshData}
                    refreshing={this.state.isRefresh}
                    ListEmptyComponent={this.renderEmpty.bind(this)}
                    ListFooterComponent={this.renderFooter.bind(this)}
                    onEndReached={this._onEndReached.bind(this)}
                    onEndReachedThreshold={0.3}
                />

                {this.state.seekingList.length > 0 && (
                    <View style={{height: 90}}></View>
                )}

            </View>
        );
    }

    renderItemView({item, index}) {
        return (
            <View style={{  marginHorizontal: 8, borderRadius: 5, marginTop: 10,}}>
                <SeekItemView item={item} buyerId={Constant.userInfo.buyerId} onPress={()=>{
                    navigation.navigate('SeekingInfoPage', {
                        id: item.id,
                    });
                }} navigation={navigation}></SeekItemView>
            </View>
        );
    }

    renderFooter() {
        if (this.state.showFoot) {
            return (
                <View style={styles.footer}>
                    {/*<ActivityIndicator size="small" color="#999999" />*/}
                    <Text style={styles.loadMoreTextStyle}>没有更多数据了</Text>
                </View>
            );
        }else {
            return null;
        }
    }

    //刷新数据
    refreshData = () => {
        this.setState(
            {
                isRefresh: true,
                pageNo: 1,
                seekingList: [],
            },
            function () {
                this.getBuyerSeekList();
            },
        );
    };

    _onEndReached() {
        if (this.state.seekingList.length == 0) {
            return;
        }
        //如果是正在加载中或没有更多数据了，则返回
        if (this.state.showFoot) {
            return null;
        }
        //底部显示正在加载更多数据
        this.setState(
            {
                pageNo: this.state.pageNo + 1,
            },
            function () {
                this.getBuyerSeekList();
            },
        );
    }

    renderEmpty() {
        return <NoData Desc="暂未发布求购信息" style={{marginTop: gREM(50)}} />;
    }

    makeCall = phoneNumber => {
        const url = `tel:${phoneNumber}`;
        Linking.canOpenURL(url)
            .then(supported => {
                if (supported) {
                    this.addPhoneHistory()
                    return Linking.openURL(url);
                } else {
                    Alert.alert('提示', '该设备不支持拨打电话');
                }
            })
            .catch(err => {
                console.error('拨号失败:', err);
                Alert.alert('错误', '无法拨打电话');
            });
    }


    // 添加拨打买手电话号码记录
    addPhoneHistory(){
        const { buyerId = 0 } = this.props.route.params || {};
        HttpUtils.postRequest(HttpUrls.addPhoneHistory, { buyerId: buyerId, type: 1 })
            .then(result => {
                console.log('addPhoneHistory', result)
            }).finally(e => {
        })
    }


}
const styles = StyleSheet.create({
    container: {
        // backgroundColor: '#F9F9F9',
        backgroundColor: '#fff',
        flex: 1,
        position: 'relative',
    },
    infoContainer: {
        marginTop: 2,
        flexDirection: 'row',
        borderBlockColor: '#E5E5E5',
        padding: 10,
        paddingHorizontal: 15,
    },
    avatarStyle: {
        width: 60,
        height: 60,
        borderRadius: 50,
    },

    nameText: {
        fontSize: 14,
        color: '#333',
        fontWeight: '500',
    },
    introText: {
        fontSize: 12,
        marginTop: 3,
    },
    regionTag: {
        backgroundColor: '#f7f7f2',
        borderRadius: 4,
        paddingVertical: 2,
        paddingHorizontal: 2,
        marginTop: 5,
        fontSize: 12,
        alignSelf: 'flex-start',
        color: '#333333',
    },

    actionButtons: {
        width: '31%',
        justifyContent: "center"
    },
    phoneButtonContainer: {
        borderRadius: 99,
        backgroundColor: '#FFDB1B',
        width: 80,
        height: 28,
        justifyContent: 'center',
        alignItems: 'center',
    },
    phoneButtonText: {
        color: '#333333',
        fontSize: 12,
    },


    preferenceContainer: {
        marginTop: 1,
        backgroundColor: '#fff',
        // padding: 10,
        paddingHorizontal: 15,
        paddingVertical:15,
    },
    sectionTitle: {
        fontSize: 15,
        color: '#333',
        fontWeight: '500',
    },
    tagsContainer: {
        flexDirection: 'row',
        flexWrap: 'wrap',
        marginTop: 5,
    },
    tagItem: {
        backgroundColor: '#fff399',
        borderRadius: 4,
        paddingVertical: 2,
        paddingHorizontal: 6,
        marginRight: 8,
        marginTop: 5,
    },
    tagItemText: {
        fontSize: 12,
        color: '#333333',
    },
    tagItemMore: {
        paddingVertical: 2,
        paddingHorizontal: 6,
        marginRight: 8,
        marginTop: 5,
        color: '#333333',
    },
    tagItemMoreText: {
        fontSize: 12
    },
    flexGrow: {
        flexGrow: 1
    },

    footer: {
        flexDirection: 'row',
        height: 40,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#F9F9F9',
    },
    loadMoreTextStyle: {
        fontSize: 14,
        color: '#999999',
        marginStart: 10,
    },


    butBox: {
        position: 'absolute',
        bottom: 20,
        left: 0,
        right: 0,
        marginHorizontal: 23,
    },
    but: {
        width: '100%',
        height: 46,
        borderRadius: 23,
        backgroundColor: '#FFE000',
        justifyContent: 'center',
        alignItems: 'center'
    },
    butText: {
        fontSize: 14,
        color: '#333'
    }


});
